package com.custom.controller;

import com.custom.contants.Constants;
import com.custom.dao.BaseDao;
import com.custom.dao.PreDao;
import com.custom.dao.PreJDBCTemplate;
import com.custom.model.MessageModel;
import com.custom.contants.Queue;
import com.custom.service.CustomeData;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

/**
 * @author wh
 * @Description
 * @date 2018/4/4 14:43
 */
@Controller
public class DataController {
    /**
     * @param message
     * @param table
     * @param action
     */
    @RequestMapping("/custom/bar")
    public void productData(@RequestParam String message, @RequestParam String table, @RequestParam String action) {
        if (StringUtils.isEmpty(message) || StringUtils.isEmpty(table)) {
            return;
        }

        MessageModel messageModel = new MessageModel();
        HashMap messageMap = new Gson().fromJson(message, HashMap.class);

        messageModel.setMessage(messageMap);
        messageModel.setTable(table);

        if (StringUtils.isEmpty(action)) {
            action = "update";
            messageModel.setActionIsNull(true);
        } else {
            messageModel.setActionIsNull(false);
        }

        messageModel.setAction(action);

        try {
            Queue.messages.put(messageModel);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(Calendar.getInstance().getTimeInMillis() - Constants.initTimeStamp.get() > Constants.updateDBMateTimeStamp.get()
                || Constants.mateMaps.size() == 0) {
            initMateMap();
            initPool();
            Constants.initTimeStamp.set(Calendar.getInstance().getTimeInMillis());
        }
    }

    private void initPool() {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Constants.initPoolSize.get());
        for (int i = 0; i < Constants.poolSize.get(); i++) {
            final int index = i;
            fixedThreadPool.execute(new Runnable() {

                public void run() {
                    while (true) {
                        Object message = null;
                        try {
                            message = Queue.messages.take();
                            dataJDBCTemplate.update(customeData.getSql(Queue.messages.take()));
                        } catch (InterruptedException e) {
                            if (null != message && ((MessageModel) message).isActionIsNull()) {
                                ((MessageModel) message).setAction("insert");
                                dataJDBCTemplate.update(customeData.getSql(message));
                            } else {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        }
    }

    private void initMateMap() {
        Constants.tables = preJDBCTemplate.getTables();

        for (String table : Constants.tables) {
            Constants.mateMaps.put(table, preJDBCTemplate.getMate(table));
        }
    }

    @Autowired
    private CustomeData customeData;

    @Autowired
    private PreDao preJDBCTemplate;

    @Autowired
    private BaseDao dataJDBCTemplate;

    private Logger log = Logger.getLogger(DataController.class.getPackage().getName());
}